/**
 * 本模块封装了Android、iOS的应用权限判断、打开应用权限设置界面、以及位置系统服务是否开启
 */
// 为 plus 声明宽松类型，避免类型报错（运行时由 uni-app 提供）
declare const plus: any;

var isIos: any
// #ifdef APP-PLUS    
isIos = (plus.os.name == "iOS")
// #endif   

var viewShow = true;
// 判断推送权限是否开启    
function judgeIosPermissionPush() {
    var result = false;
    var UIApplication = plus.ios.import("UIApplication");
    var app = UIApplication.sharedApplication();
    var enabledTypes = 0;
    if (app.currentUserNotificationSettings) {
        var settings = app.currentUserNotificationSettings();
        enabledTypes = settings.plusGetAttribute("types");
        if (enabledTypes == 0) {
            console.log("推送权限没有开启");
        } else {
            result = true;
            console.log("已经开启推送功能!")
        }
        plus.ios.deleteObject(settings);
    } else {
        enabledTypes = app.enabledRemoteNotificationTypes();
        if (enabledTypes == 0) {
            console.log("推送权限没有开启!");
        } else {
            result = true;
            console.log("已经开启推送功能!")
        }
    }
    plus.ios.deleteObject(app);
    plus.ios.deleteObject(UIApplication);
    return result;
}

// 判断定位权限是否开启    
function judgeIosPermissionLocation() {
    var result = false;
    var cllocationManger = plus.ios.import("CLLocationManager");
    var status = cllocationManger.authorizationStatus();
    result = (status != 2)
    plus.ios.deleteObject(cllocationManger);
    return result;
}

// 判断麦克风权限是否开启    
function judgeIosPermissionRecord() {
    var result = false;
    var avaudiosession = plus.ios.import("AVAudioSession");
    var avaudio = avaudiosession.sharedInstance();
    var permissionStatus = avaudio.recordPermission();
    console.log("permissionStatus:" + permissionStatus);
    if (permissionStatus == 1684369017 || permissionStatus == 1970168948) {
        console.log("麦克风权限没有开启");
    } else {
        result = true;
        console.log("麦克风权限已经开启");
    }
    plus.ios.deleteObject(avaudiosession);
    return result;
}

// 判断相机权限是否开启    
function judgeIosPermissionCamera() {
    var result = false;
    var AVCaptureDevice = plus.ios.import("AVCaptureDevice");
    // 修正媒体类型字符串，使用 'video'
    var authStatus = AVCaptureDevice.authorizationStatusForMediaType('video');
    console.log("authStatus:" + authStatus);
    if (authStatus == 3) {
        result = true;
        console.log("相机权限已经开启");
    } else {
        console.log("相机权限没有开启");
    }
    plus.ios.deleteObject(AVCaptureDevice);
    return result;
}

// 判断相册权限是否开启    
function judgeIosPermissionPhotoLibrary() {
    var result = false;
    var PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
    var authStatus = PHPhotoLibrary.authorizationStatus();
    console.log("authStatus:" + authStatus);
    if (authStatus == 3) {
        result = true;
        console.log("相册权限已经开启");
    } else {
        console.log("相册权限没有开启");
    }
    plus.ios.deleteObject(PHPhotoLibrary);
    return result;
}

// 判断通讯录权限是否开启    
function judgeIosPermissionContact() {
    var result = false;
    var CNContactStore = plus.ios.import("CNContactStore");
    var cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
    if (cnAuthStatus == 3) {
        result = true;
        console.log("通讯录权限已经开启");
    } else {
        console.log("通讯录权限没有开启");
    }
    plus.ios.deleteObject(CNContactStore);
    return result;
}

// 判断日历权限是否开启    
function judgeIosPermissionCalendar() {
    var result = false;
    var EKEventStore = plus.ios.import("EKEventStore");
    var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(0);
    if (ekAuthStatus == 3) {
        result = true;
        console.log("日历权限已经开启");
    } else {
        console.log("日历权限没有开启");
    }
    plus.ios.deleteObject(EKEventStore);
    return result;
}

// 判断备忘录权限是否开启    
function judgeIosPermissionMemo() {
    var result = false;
    var EKEventStore = plus.ios.import("EKEventStore");
    var ekAuthStatus = EKEventStore.authorizationStatusForEntityType(1);
    if (ekAuthStatus == 3) {
        result = true;
        console.log("备忘录权限已经开启");
    } else {
        console.log("备忘录权限没有开启");
    }
    plus.ios.deleteObject(EKEventStore);
    return result;
}

// Android权限查询    
function requestAndroidPermission(permissionIDS: string) {
    return new Promise((resolve, reject) => {
        const permissions = permissionIDS.split(",");
        console.log('开始申请权限:', permissions);
        
        plus.android.requestPermissions(  
            permissions,
            function (resultObj: any) {
                console.log('权限申请结果:', resultObj);
                var result = 0;
                var grantedCount = 0;
                var deniedCount = 0;
                var alwaysDeniedCount = 0;
                
                // 统计已授权的权限
                for (var i = 0; i < resultObj.granted.length; i++) {
                    var grantedPermission = resultObj.granted[i];
                    console.log('已获取的权限：' + grantedPermission);
                    grantedCount++;
                }
                
                // 统计本次拒绝的权限
                for (var i = 0; i < resultObj.deniedPresent.length; i++) {
                    var deniedPresentPermission = resultObj.deniedPresent[i];
                    console.log('拒绝本次申请的权限：' + deniedPresentPermission);
                    deniedCount++;
                }
                
                // 统计永久拒绝的权限
                for (var i = 0; i < resultObj.deniedAlways.length; i++) {
                    var deniedAlwaysPermission = resultObj.deniedAlways[i];
                    console.log('永久拒绝申请的权限：' + deniedAlwaysPermission);
                    alwaysDeniedCount++;
                }
                
                // 判断最终结果
                if (alwaysDeniedCount > 0) {
                    result = -1; // 有权限被永久拒绝
                } else if (deniedCount > 0) {
                    result = 0; // 有权限被拒绝但可以重新申请
                } else if (grantedCount > 0) {
                    result = 1; // 至少有一个权限被授权
                } else {
                    result = 0; // 没有权限被授权
                }
                
                console.log(`权限申请完成: 授权${grantedCount}个, 拒绝${deniedCount}个, 永久拒绝${alwaysDeniedCount}个, 结果: ${result}`);
                resolve(result);
            },
            function (error: any) {
                console.log('申请权限错误：' + error.code + " = " + error.message);
                resolve({
                    code: error.code,
                    message: error.message
                });
            }
        );
    });
}

// 使用一个方法，根据参数判断权限    
function judgeIosPermission(permissionID: string) {
    if (permissionID == "location") {
        return judgeIosPermissionLocation()
    } else if (permissionID == "camera") {
        return judgeIosPermissionCamera()
    } else if (permissionID == "photoLibrary") {
        return judgeIosPermissionPhotoLibrary()
    } else if (permissionID == "record") {
        return judgeIosPermissionRecord()
    } else if (permissionID == "push") {
        return judgeIosPermissionPush()
    } else if (permissionID == "contact") {
        return judgeIosPermissionContact()
    } else if (permissionID == "calendar") {
        return judgeIosPermissionCalendar()
    } else if (permissionID == "memo") {
        return judgeIosPermissionMemo()
    }
    return false;
}

// 跳转到**应用**的权限页面    
function gotoAppPermissionSetting() {
    if (isIos) {
        var UIApplication = plus.ios.import("UIApplication");
        var application2 = UIApplication.sharedApplication();
        var NSURL2 = plus.ios.import("NSURL");
        var setting2 = NSURL2.URLWithString("app-settings:");
        application2.openURL(setting2);

        plus.ios.deleteObject(setting2);
        plus.ios.deleteObject(NSURL2);
        plus.ios.deleteObject(application2);
    } else {
        // console.log(plus.device.vendor);    
        var Intent: any = plus.android.importClass("android.content.Intent");
        var Settings: any = plus.android.importClass("android.provider.Settings");
        var Uri: any = plus.android.importClass("android.net.Uri");
        var mainActivity: any = plus.android.runtimeMainActivity();
        var intent: any = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        var uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
        intent.setData(uri);
        mainActivity.startActivity(intent);
    }
}

// 检查系统的GPS设备服务是否开启
function checkSystemEnableLocation() {
    if (isIos) {
        var result: boolean = false;
        var cllocationManger = plus.ios.import("CLLocationManager");
        result = cllocationManger.locationServicesEnabled();
        console.log("系统定位开启:" + result);
        plus.ios.deleteObject(cllocationManger);
        return result;
    } else {
        var context: any = plus.android.importClass("android.content.Context");
        var locationManager: any = plus.android.importClass("android.location.LocationManager");
        var main: any = plus.android.runtimeMainActivity();
        var mainSvr = main.getSystemService(context.LOCATION_SERVICE);
        var result: boolean = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
        console.log("系统定位开启:" + result);
        return result
    }
}

let permissionMap = {
    "android": {
        "CAMERA_EXTERNAL_STORAGE": {
            "name": "android.permission.READ_EXTERNAL_STORAGE,android.permission.WRITE_EXTERNAL_STORAGE,android.permission.CAMERA",
            "title": "相机/相册权限",
            "content": "用于拍照或录制视频、上传内容、更换头像等。"
        },
        "CAMERA": {
            "name": "android.permission.CAMERA",
            "title": "相机权限",
            "content": "用于拍照或录制视频、上传内容、更换头像等。"
        },
        "EXTERNAL_STORAGE": {
            "name": "android.permission.READ_EXTERNAL_STORAGE,android.permission.WRITE_EXTERNAL_STORAGE",
            "title": "相册权限",
            "content": "用于访问相册中的图片，上传照片、更换头像等。"
        },
        "MEDIA_IMAGES": {
            "name": "android.permission.READ_MEDIA_IMAGES",
            "title": "相册权限",
            "content": "用于访问相册中的图片，上传照片、更换头像等。"
        },
        "MEDIA_VISUAL_SELECTED": {
            "name": "android.permission.READ_MEDIA_VISUAL_USER_SELECTED",
            "title": "相册权限",
            "content": "用于访问您选择的照片，上传图片、更换头像等。"
        },
        "LOCATION": {
            "name": "android.permission.ACCESS_COARSE_LOCATION,android.permission.ACCESS_FINE_LOCATION",
            "title": "地理位置权限",
            "content": "用于提供定位导航、附近搜索等基于位置的服务。"
        },
        "CALL_PHONE": {
            "name": "android.permission.CALL_PHONE",
            "title": "拨打/管理电话权限",
            "content": "用于联系买家或客服，发起电话拨打。"
        },

    },
    "ios": {}
}

let view: any = null;

function showViewDesc(permission: string) {
    let plat = isIos ? "ios" : "android";
    const NativeView: any = plus && plus.nativeObj && plus.nativeObj.View;
    view = new NativeView('per-modal', {
        top: '0px',
        left: '0px',
        width: '100%',
        backgroundColor: 'rgba(0,0,0,0.2)',
    })
    view.drawRect({
        color: '#fff',
        radius: '5px'
    }, {
        top: '50px',
        left: '5%',
        width: '90%',
        height: "100px",
    })
    view.drawText((permissionMap as any)[plat][permission]["title"], {
        top: '60px',
        left: "8%",
        height: "30px"
    }, {
        align: "left",
        color: "#000",
    })
    view.drawText((permissionMap as any)[plat][permission]["content"], {
        top: '85px',
        height: "60px",
        left: "8%",
        width: "84%"
    }, {
        whiteSpace: 'normal',
        size: "14px",
        align: "left",
        color: "#656563"
    })
    setTimeout(() => {
        if (viewShow) view.show()
    }, 200)
}

function permissionCheck(permission: string) {
    return new Promise(async (resolve, reject) => {
        let plat = isIos ? "ios" : "android";
        // #ifdef H5
        resolve(1)
        // #endif
        // #ifdef APP-PLUS
        if (isIos) {   
            // const camera = permission.judgeIosPermission("camera");//判断ios是否给予摄像头权限    
            // //ios相册没权限，系统会自动弹出授权框    
            // //let photoLibrary = permission.judgeIosPermission("photoLibrary");//判断ios是否给予相册权限    
            // if(camera){    
            //     resolve();    
            // }else{    
            //     reject('需要开启相机使用权限');    
            // }    
            resolve(1)
        } else { // android    
            // 检测华为设备，参考CSDN文章的处理方式
            let model = '';
            let manufacturer = '';
            try {
                const systemInfo = uni.getSystemInfoSync();
                model = (systemInfo.brand || '').toLowerCase();
                manufacturer = ((systemInfo as any).manufacturer || '').toLowerCase();
            } catch (error) {
                console.error('获取系统信息失败:', error);
            }
            const isHuawei = model === 'huawei' || model === '华为' || model === 'honor' || model === '荣耀' || manufacturer === 'huawei' || manufacturer === '华为' || manufacturer === 'honor' || manufacturer === '荣耀';
            
            let permission_arr = (permissionMap as any)[plat][permission]["name"].split(",");
            let hasPermission = true;
            let needRequest = false;
            let isDenied = false;
            
            // 检查每个权限的状态
            for (let i = 0; i < permission_arr.length; i++) {
                let status = plus.navigator.checkPermission(permission_arr[i]);
                if (status === "denied" || status === "undetermined") {
                    hasPermission = false;
                    if (status === "undetermined") {
                        needRequest = true;
                    } else if (status === "denied") {
                        isDenied = true;
                    }
                }
            }
            
            // 华为设备特殊处理：无论什么情况都显示权限说明弹窗
            if (isHuawei) {
                console.log('华为设备，强制显示权限说明弹窗');
                showViewDesc(permission);
                setTimeout(() => {
                    requestAndroidPermission((permissionMap as any)[plat][permission]["name"]).then((res) => {
                        viewShow = false;
                        setTimeout(() => {
                            viewShow = true;
                        }, 120)
                        view.close();
                        
                        if (res == -1) {
                            uni.showModal({
                                title: '提示',
                                content: '操作权限被拒绝，请手动前往设置',
                                confirmText: "去设置",
                                success: (res) => {
                                    if (res.confirm) {
                                        gotoAppPermissionSetting()
                                    }
                                }
                            })
                        } else if (res == 1) {
                            console.log('权限申请成功');
                        } else {
                            console.log('权限申请被拒绝，但可以重新申请');
                        }
                        resolve(res)
                    }).catch((error) => {
                        console.error('权限申请异常:', error);
                        viewShow = false;
                        setTimeout(() => {
                            viewShow = true;
                        }, 120)
                        view.close();
                        resolve(0)
                    })
                }, 1000); // 延迟1秒让用户看到权限说明
                return;
            }
            // 非华为设备的处理逻辑
            // 在Android 15+上，如果权限状态不明确，直接尝试申请
            const androidVersion = plus.os.version || '0';
            const majorVersion = parseInt(androidVersion.split('.')[0]) || 0;
            
            if (majorVersion >= 15) {
                // Android 15+：若已拥有权限，直接放行，避免二级授权场景下的自定义提示
                if (hasPermission) {
                    resolve(1)
                    return
                }

                // 未授权时再展示说明并发起申请
                showViewDesc(permission);
                setTimeout(() => {
                    requestAndroidPermission((permissionMap as any)[plat][permission]["name"]).then((res) => {
                        viewShow = false;
                        setTimeout(() => {
                            viewShow = true;
                        }, 120)
                        view.close();
                        
                        if (res == -1) {
                            uni.showModal({
                                title: '提示',
                                content: '操作权限被拒绝，请手动前往设置',
                                confirmText: "去设置",
                                success: (res) => {
                                    if (res.confirm) {
                                        gotoAppPermissionSetting()
                                    }
                                }
                            })
                        } else if (res == 1) {
                            console.log('权限申请成功');
                        } else {
                            console.log('权限申请被拒绝，但可以重新申请');
                        }
                        resolve(res)
                    }).catch((error) => {
                        console.error('权限申请异常:', error);
                        viewShow = false;
                        setTimeout(() => {
                            viewShow = true;
                        }, 120)
                        view.close();
                        resolve(0)
                    })
                }, 1000); // 延迟1秒让用户看到权限说明
            } else if (!hasPermission) {
                if (needRequest) {
                    // 权限未确定，直接申请权限
                    requestAndroidPermission((permissionMap as any)[plat][permission]["name"]).then((res) => {
                        if (res == -1) {
                            // 权限被永久拒绝
                            uni.showModal({
                                title: '提示',
                                content: '操作权限被拒绝，请手动前往设置',
                                confirmText: "去设置",
                                success: (res) => {
                                    if (res.confirm) {
                                        gotoAppPermissionSetting()
                                    }
                                }
                            })
                        }
                        resolve(res)
                    })
                } else {
                    // 权限被拒绝，显示说明后申请
                    showViewDesc(permission);
                    requestAndroidPermission((permissionMap as any)[plat][permission]["name"]).then((res) => {
                        viewShow = false;
                        setTimeout(() => {
                            viewShow = true;
                        }, 120)
                        view.close();
                        if (res == -1) {
                            uni.showModal({
                                title: '提示',
                                content: '操作权限被拒绝，请手动前往设置',
                                confirmText: "去设置",
                                success: (res) => {
                                    if (res.confirm) {
                                        gotoAppPermissionSetting()
                                    }
                                }
                            })
                        }
                        resolve(res)
                    })
                }
            } else {
                resolve(1)
            }
        }
        // #endif
    })
}

const permissionApi: any = {
    permissionCheck,
    judgeIosPermission,
    requestAndroidPermission,
    checkSystemEnableLocation,
    gotoAppPermissionSetting
}

export default permissionApi